﻿Imports System.Data.SqlClient
Public Class FormCustomer

    Public Sub RefreshData()

        DataGridView1.Rows.Clear()

        Dim cn As New SqlConnection
        cn.ConnectionString = "server=.;uid=sa;pwd=123;database=SaleDb"
        cn.Open()

        Dim cmd As New SqlCommand
        cmd.Connection = cn
        cmd.CommandText = "SELECT * FROM Customer WHERE CustomerName LIKE N'%" & txtSearch.Text & "%'OR PhoneNumber LIKE N'%" & txtSearch.Text & "%'"
        Dim reader As SqlDataReader = cmd.ExecuteReader()
        While reader.Read
            DataGridView1.Rows.Add(reader.GetValue(0), reader.GetValue(1), reader.GetValue(2), reader.GetValue(3))
        End While
        reader.Close()

    End Sub

    Private Sub FormCustomer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        Me.RefreshData()


    End Sub
   

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

        Dim frm As New FormCustomerEditor()
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then

            Me.RefreshData()

        End If
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click

        If Me.DataGridView1.SelectedRows.Count = 0 Then
            Exit Sub
        End If
        Dim row As DataGridViewRow = Me.DataGridView1.SelectedRows(0)
        Dim frm As New FormCustomerEditor()
        frm.txtCustomerId.Text = row.Cells("CustomerId").Value
        frm.txtCustomerName.Text = row.Cells("CustomerName").Value
        frm.txtPhone.Text = row.Cells("Phone").Value
        frm.txtAddress.Text = row.Cells("Address").Value

        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then

            Me.RefreshData()

        End If
    End Sub

    Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged

        Me.RefreshData()

    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Me.DataGridView1.SelectedRows.Count = 0 Then
            Exit Sub
        End If

        If MessageBox.Show("Are you sure want to delete?", "Delete", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then

            Exit Sub
        End If

        Dim row As DataGridViewRow = Me.DataGridView1.SelectedRows(0)

        Dim id = row.Cells("CustomerId").Value

        Dim cn As New SqlConnection
        cn.ConnectionString = "server=.;uid=sa;pwd=123;database=SaleDb"
        cn.Open()


        Dim cmd As New SqlCommand
        cmd.Connection = cn
        cmd.CommandText = "DELETE  FROM Customer WHERE CustomerId = " & id
        cmd.ExecuteNonQuery()

        Me.RefreshData()


    End Sub

   
End Class



